<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="创建新单体"
          @back="goBack"
        >
        </el-page-header>
        <div class="card-box--downloadbtn">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="isSending"
            >保存</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        class="content-box"
        label-width="120px"
      >
        <el-form-item label="单体工程名称" prop="engineerName">
          <el-input
            v-model.trim="formData.engineerName"
            class="width-custom width-custom240"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="负责人" prop="leaderInfo">
          <el-select
            v-model="formData.leaderInfo"
            filterable
            clearable
            remote
            placeholder="请输入姓名"
            :remote-method="getUserData"
            value-key="value"
            class="width-custom240"
          >
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.label"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设置工程类型" prop="projectTypeModel">
          <div class="m-4">
            <el-cascader
              v-model="formData.projectTypeModel"
              :show-all-levels="false"
              @change="handleChange"
              :options="engineeringList"
              :props="props2"
              ref="cascader"
              collapse-tags
              collapse-tags-tooltip
              clearable
              class="width-custom240"
            />
          </div>
        </el-form-item>

        <el-form-item label="工程类型">
          <span
            class="text--info form-detail section"
            v-for="(item, index) in engineerTypeArray"
            :key="index"
            >{{ item }}</span
          >
        </el-form-item>

        <el-form-item label="子工程类型">
          <span
            class="text--info form-detail section"
            v-for="(item, index) in ext1Array"
            :key="index"
            >{{ item }}</span
          >
        </el-form-item>

        <el-form-item label="分部">
          <span
            class="text--info form-detail section"
            v-for="(item, index) in fbTypeArray"
            :key="index"
            >{{ item }}</span
          >
        </el-form-item>

        <el-form-item label="子分部">
          <span
            class="text--info form-detail section"
            v-for="(item, index) in zfbTypeArray"
            :key="index"
            >{{ item }}</span
          >
        </el-form-item>

        <el-form-item label="分项">
          <span
            class="text--info form-detail section"
            v-for="(item, index) in fxTypeArray"
            :key="index"
            >{{ item }}</span
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, PropType } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  updateMonomer,
  addMonomer,
  getBaseTree,
  getMonomerInfo
} from "/@/api/projects";
import { getUserList } from "/@/api/user";
import NotifMessage from "/@/utils/message/notification";
import { ModeType, RoleInfoType } from "../types";
import { storageLocal } from "/@/utils/storage";
export default defineComponent({
  props: {
    mode: {
      type: String as PropType<ModeType>,
      require: true,
      default: "add"
    },
    roleInfo: {
      type: Object as PropType<RoleInfoType>,
      require: false,
      default: null
    }
  },
  emits: ["emitClose"],
  setup() {
    const route = useRoute();
    const isSending = ref(false);
    const router = useRouter();
    let formRef = ref<HTMLFormElement | null>(null) as any;
    const cascader = ref<HTMLFormElement | null>(null) as any;
    const monomerId = route?.query?.id;
    let projectInfo = storageLocal.getItem("projectInfo");
    let sectionInfo = storageLocal.getItem("sectionInfo");
    // const monomerInfoProp = toRef(props, "roleInfo");
    let userList = ref([]);
    let state = reactive({
      formData: {
        engineerName: "",
        leaderName: "",
        leaderId: "",
        leaderInfo: "" as any,
        sectionId: sectionInfo.id,
        projectManageId: projectInfo.id,
        secEngineerList: [],
        engineerTypeName: "",
        ext1: "",
        fbTypeName: "",
        zfbTypeName: "",
        fxTypeName: "",
        projectTypeModel: "" as any
      },
      engineerTypeArray: [],
      ext1Array: [],
      fbTypeArray: [],
      zfbTypeArray: [],
      fxTypeArray: [],
      engineeringList: [],
      props2: {
        multiple: true,
        value: "id",
        label: "itemText",
        emitPath: false //只返回改节点的值
      }
    });

    const formRules = ref({
      engineerName: [
        { required: true, message: "请输入单体工程名称", trigger: "blur" }
      ],
      leaderInfo: [
        { required: true, message: "请选择负责人", trigger: "change" }
      ],
      projectTypeModel: [
        { required: true, message: "请设置工程类型", trigger: "change" }
      ]
    });

    //过滤最后一级children为空数组数据
    const getTreeData = data => {
      for (var i = 0; i < data.length; i++) {
        if (data[i]?.children?.length) {
          // children若不为空数组，则继续 递归调用 本方法
          data[i].isLast = false;
          getTreeData(data[i].children);
        } else {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
          data[i].isLast = true; //判断是否最后一级
        }
      }
      return data;
    };

    // 工程类型
    const getProjectBaseList = async () => {
      try {
        const { data } = await getBaseTree({
          pageNum: 1,
          pageSize: 0,
          belongType: 1
        });
        state.engineeringList = getTreeData(data) || [];
      } catch (err) {
        console.log(err);
      }
    };

    const handleChange = () => {
      let secEngineerList = [];
      // const obj = proxy.$refs['cascader'].getCheckedNodes() //标签上定义的 ref值
      state.engineerTypeArray = [];
      state.ext1Array = [];
      state.fbTypeArray = [];
      state.zfbTypeArray = [];
      state.fxTypeArray = [];
      const obj = cascader.value.getCheckedNodes();
      const data = obj.filter(item => item?.data?.isLast);
      data.forEach(item => {
        state.engineerTypeArray.push(item.pathLabels[0]);
        state.ext1Array.push(item.pathLabels[1]);
        state.fbTypeArray.push(item.pathLabels[2]);
        state.zfbTypeArray.push(item.pathLabels[3]);
        state.fxTypeArray.push(item.pathLabels[4]);
        if (item?.pathNodes?.length) {
          item.pathNodes.forEach(obj => {
            secEngineerList.push({
              parentId: obj.data.parentId,
              selectId: obj.data.id,
              selectName: obj.data.itemText,
              selectType: obj.data.itemType,
              belongType: 1
            });
          });
        }
      });
      state.engineerTypeArray = unique(state.engineerTypeArray);
      state.ext1Array = unique(state.ext1Array);
      state.fbTypeArray = unique(state.fbTypeArray);
      state.zfbTypeArray = unique(state.zfbTypeArray);
      state.fxTypeArray = unique(state.fxTypeArray);
      let secEngineerListArray = uniqueObject(secEngineerList, "selectId");
      state.formData.secEngineerList = secEngineerListArray;
    };

    const unique = arr => {
      return Array.from(new Set(arr));
    };

    const uniqueObject = (arr, key) => {
      let set = [];
      let result = [];
      for (let val of arr) {
        if (!set.includes(val[key])) {
          result.push(val);
          set.push(val[key]);
        }
      }
      return result;
    };

    const onAddRole = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        let params = Object.assign(state.formData);
        const { code, message } = await addMonomer(params);
        if (code === 200) {
          NotifMessage.success("添加成功");
          goBack();
        } else {
          NotifMessage.error(message);
        }
      } catch (error) {
        console.log(error);
      }
    };

    const onUpdateRole = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        let params = Object.assign({ id: monomerId }, state.formData);
        const { code, message } = await updateMonomer(params);
        if (code === 200) {
          NotifMessage.success("编辑成功");
          goBack();
        } else {
          NotifMessage.error(message);
        }
      } catch (error) {
        console.log(error);
      }
    };

    //获取项目组成员
    const getUserData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const getMonomerDetail = async () => {
      try {
        const { code, data } = await getMonomerInfo({ id: monomerId });
        if (code === 200) {
          state.formData = data || [];
          state.engineerTypeArray = data?.engineerTypeName.split(",");
          state.ext1Array = data?.ext1.split(",");
          state.fbTypeArray = data?.fbTypeName.split(",");
          state.zfbTypeArray = data?.zfbTypeName.split(",");
          state.fxTypeArray = data?.fxTypeName.split(",");
          state.formData.leaderInfo = {
            value: +data?.leaderId,
            label: data?.leaderName
          };
          userList.value = [state.formData.leaderInfo];
          const projectTypeModel = data.secEngineerList.filter(item => {
            return item.selectType === "D";
          });
          state.formData.projectTypeModel = projectTypeModel.map(item => {
            return item.selectId;
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const goBack = () => {
      router.push("/projectsS/proManage/monomer");
    };

    const handleSubmit = () => {
      state.formData.leaderId = state.formData.leaderInfo.value;
      state.formData.leaderName = state.formData.leaderInfo.label;
      state.formData.engineerTypeName = state.engineerTypeArray.join();
      state.formData.ext1 = state.ext1Array.join();
      state.formData.fbTypeName = state.fbTypeArray.join();
      state.formData.zfbTypeName = state.zfbTypeArray.join();
      state.formData.fxTypeName = state.fxTypeArray.join();
      state.formData.leaderId = state.formData.leaderInfo.value;
      state.formData.leaderName = state.formData.leaderInfo.label;
      isSending.value = true;
      if (monomerId) {
        onUpdateRole();
      } else {
        onAddRole();
      }
    };
    if (monomerId) {
      getMonomerDetail();
    }
    getProjectBaseList();
    return {
      formRef,
      ...toRefs(state),
      formRules,
      goBack,
      isSending,
      handleSubmit,
      getUserData,
      userList,
      cascader,
      handleChange
    };
  }
});
</script>

<style lang="scss" scoped>
.section {
  min-width: auto !important;
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
